var v8 = require('v8');
var fs = require('fs');
const vm = require('vm');
const { exit } = require('process');
v8.setFlagsFromString('--no-lazy');
if (Number.parseInt(process.versions.node, 10) >= 12) {
    v8.setFlagsFromString('--no-flush-bytecode');
}

const readSourceHash = function (bytecodeBuffer) {
    if (!Buffer.isBuffer(bytecodeBuffer)) {
        throw new Error('bytecodeBuffer must be a buffer object.');
    }
    if (process.version.startsWith('v8.8') || process.version.startsWith('v8.9')) {
        return bytecodeBuffer.subarray(12, 16).reduce((sum, number, power) => sum += number * Math.pow(256, power), 0);
    } else {
        return bytecodeBuffer.subarray(8, 12).reduce((sum, number, power) => sum += number * Math.pow(256, power), 0);
    }
};

global.SOFTNAME = "阔老板_阔软工作室";
global.SOFTVER = "2025.4.10";
global.SOFTHTTP = "https://www.kuosoft.com/";
global.DIR = global.dir = __dirname + "/";
global.temp = dir + "temp/";
global.TPL = dir + "config/";
global.Controller = dir + "Controller/";
global.WWW = dir + "www";
global.p = console.log;
const argv = process.argv;
var filename = "kuo";
var Action = argv[2];
if (!filename) {
    console.log("file does not exist");
    exit();
}

if (!Action) {
    console.log("Action does not exist");
    exit();
}

var ActionList = {
    "b": "编译",
    "r": "编译正式运行",
    "br": "编译运行",
};

if (!ActionList[Action]) {
    console.log("Action does not exist [b r br]");
    exit();
}

var filePath = __dirname + "/" + filename + ".js";
var filePath__ = __dirname + "/" + filename + "ServerLess.js";
var jscode = "";

function zimulu(mulu) {
    mulu = mulu.replace(/Kuo_/g, '')
    try {
        let files = fs.readdirSync(Controller + mulu);
        var time = [];
        files.forEach(file => {

            if (file.indexOf(".js") > -1) {
                var wjian = file.split(".js");
                var neirong = fs.readFileSync(Controller + mulu + "/" + file, "utf-8");
                var neirong_ = neirong.split("\n");
                neirong_.shift();
                neirong_.pop();
                time.push(wjian[0] + ":" + (neirong_.join("\n")));
            } else {
                if (file != ".DS_Store" && file.indexOf(".") <= -1) {
                    time.push(zimulu(mulu + '/' + file));
                }
            }
        });
        return time.join(",");
    } catch (error) {
        return '';
    }
}

function srccode() {
    var code = "";
    let files = fs.readdirSync(Controller);
    files.forEach(file => {
        if (file.indexOf(".js") > -1) {
            var wjian = file.split(".js");
            var neirong = fs.readFileSync(Controller + file, "utf-8");
            if (neirong.indexOf("module.exports") > -1) {
                var neirong_ = neirong.split("\n");
                neirong_.pop();
                neirong_.push(`global['` + wjian[0] + `'] = ` + wjian[0] + `;`)
                code += neirong_.join("\n") + "\n";
            } else {
                var neirong_ = [];
                var huodex = neirong.split("\n");
                neirong_.push(`var ` + wjian[0] + ` = {`);

                for (var i = 1; i < huodex.length - 1; i++) {
                    neirong_.push(huodex[i]);
                }

                let zimux = zimulu(wjian[0]);
                if (zimux && zimux != "") {
                    neirong_.push("," + zimux);
                }
                neirong_.push(`}`);
                neirong_.push(`global['` + wjian[0] + `'] = ` + wjian[0] + `;`)
                code += neirong_.join("\n") + "\n";
            }
        }
    });
    return code;
}
try {
    jscode = fs.readFileSync(filePath).toString();
} catch (err) {
    console.log("file does not exist!");
    exit();
}
var codejs = `"use strict";
console.log("`+ global.SOFTNAME + ` v` + global.SOFTVER + ` ` + global.SOFTHTTP + `");
global.SOFTNAME = "`+ global.SOFTNAME + `";
global.SOFTVER = "`+ global.SOFTVER + `";
global.SOFTHTTP = "`+ global.SOFTHTTP + `";
global.DIR = global.dir = __dirname+"/";
global.temp = dir+"temp/";
global.TPL = dir+"config/";
global.Controller = dir+"Controller/";
global.WWW = dir+"www";
global.p = console.log;
require(TPL+"KuoSoft.com");
`;
let changdus = 0;
var CODEJS = null;
if (Action == "r" || Action == "b" || Action == "br") {
    var js_code = "\n((exports, require, module, __filename, __dirname,process,global) =>{\n";
    var srccode_ = srccode();
    let chaikai =  jscode.split('//@//////TIHUAN/////////@//');
    var yunwenjian = codejs +chaikai[0]+srccode_+chaikai[1];
    js_code += yunwenjian;
    js_code += "\n});";
    //云部署
    fs.writeFileSync(filePath__,  yunwenjian);
    if (Action == "r") {
        require(filePath__);
        return;
    }

    try {
        var script = new vm.Script(js_code, { produceCachedData: true });
        let bytecodeBuffer = (script.createCachedData && script.createCachedData.call)
            ? script.createCachedData()
            : script.cachedData;
        changdus = readSourceHash(bytecodeBuffer);
        CODEJS = Buffer.from(bytecodeBuffer).toString('base64');
        console.log("Compiled successfully " + Action);
    } catch (error) {
        console.log("Compiled error " + error);
    }
}

if (Action == "br") {
    let dummyCode = '';
    let byte_code2 = Buffer.from(CODEJS, 'base64');
    if (changdus > 1) {
        dummyCode = '"' + '\u200b'.repeat(changdus - 2) + '"'; // "\u200b" Zero width space
    }

    script = new vm.Script(dummyCode, { cachedData: byte_code2 });
    var fan = script.runInThisContext();
    fan.apply(module.exports, [exports, require, module, __filename, __dirname, process, global]);
    console.log("execution succeed " + Action);
}
var RUN = `var v8 = require('v8');
var fs = require('fs');
const vm = require('vm');
v8.setFlagsFromString('--no-lazy');
if (Number.parseInt(process.versions.node, 10) >= 12) {
  v8.setFlagsFromString('--no-flush-bytecode');
}
var byte_code = Buffer.from(\``+ CODEJS + `\`,'base64');
let dummyCode = '';
let changdus = `+ changdus + `;
if (changdus > 1) {
    dummyCode = '"' + '\u200b'.repeat(changdus - 2) + '"'; 
}
var script = new vm.Script(dummyCode, {cachedData: byte_code});
var fan = script.runInThisContext();
fan.apply(module.exports,[exports, require, module, __filename, __dirname,process,global]);
console.log("Compiled successfully ");`;
fs.writeFileSync(__dirname + "/kuo.bin", RUN);